function getStoraged(key) {
	const data = uni.getStorageSync(key);
	if (data) {
		return data;
	} else {
		return false;
	}
}

function setStoraged(key, value) {
	uni.setStorage({
		key: key,
		data: value,
	});
};
import config from "../../config.js"; // 获取配置文件中的IP和端口号码的写入名称或值的数组元素，;
// 设置公共路径
const baseUrl = config.baseUrl;
// 异步请求
const requestSync = (
	url = "",
	data = {},
	type = "POST",
	header = {
		// "content-type": "application/json;charset=utf-8",
		// "content-type": "application/json;charset=utf-8",
		"content-type": "application/json;charset=utf-8",
		'cache-control': 'no-cache',
		'Access-Control-Allow-Headers': 'appId',
		'Access-Control-Allow-Methods': 'POST,GET,OPTIONS',
		'Access-Control-Max-Age': 86400,
		// "content-type": "application/json;charset=UTF8",
		"authration_token": getStoraged("authration_token") ? getStoraged("authration_token") : "",
		// user_id: getStoraged("user_id"),
	}
) => {
	return new Promise((resolve, reject) => {
		header.authration_token = getStoraged("authration_token").length ? getStoraged("authration_token") :
			"";
		header.user_id = getStoraged("user_id");

		uni
			.request({
				method: type,
				//#ifdef MP-WEIXIN
				url: baseUrl + url, //微信中的请求路径
				//#endif
				//#ifdef H5 || APP-PLUS 
				url: url, //H5中的请求路径
				//#endif
				data: data,
				header: header,
				// dataType: "json",
			})
			.then(response => {
				// setTimeout(function () {
				//   uni.hideLoading();
				// }, 200);
				let [error, res] = response;
				if (res.data.code == 200) {
					resolve(res.data);
				} else if (res.data.code == 403) {
					let arr = ["/user/status", "/collects/set"]
					if (!arr.includes(url)) {
						uni.showToast({
							title: "当前操作需要登录",
							icon: "none",
							duration: 2000,
							success: () => {
								setTimeout(() => {
									uni.navigateTo({
										url: "/pages2/login",
									});
								}, 2000);
							},
						});
					}
				}
			})
			.catch(error => {
				let [err, res] = error;
				reject(err);
			});
	});
};
const state = {
	systemInfo: uni.getStorageSync("systemInfo") || null,
	userInfo: uni.getStorageSync("userInfo") || null,
	userStatus: "",
	showMfsjf: uni.getStorageSync("showMfsjf") || 0,
	userId: uni.getStorageSync("user_id") || "", //用户id 用户自己创建的时候取决于自己的appid 如果appid不
}

const mutations = {
	setSystemInfo(state, data) {
		// uni.setStorageSync("systemInfo", data);
		state.systemInfo = data
	},
	setUserInfo(state, userInfo) {
		if (userInfo.integral <= 3) {
			setStoraged('showMfsjf', 1)
		}
		setStoraged('userInfo', userInfo)
		setStoraged('user_id', userInfo.id);
		// setStoraged('authration_token', userInfo.id);
		setStoraged('phone', JSON.parse(userInfo.phone))
		state.phone = userInfo.phone;
		state.userInfo = userInfo
	},
	setUserStatus(state, statsu) {
		state.userStatus = statsu
	},
	setPhone(state, phone) {
		setStoraged('phone', phone)
		state.phone = phone;
	},
	loginInfo(state, data) {
		console.log("113", data);
		state.userStatus = data.status;
		state.userInfo = data.userInfo;
		console.log(state.userStatus)
	}
}

const actions = {
	async setUserInfo({
		commit,
		dispatch
	}, data) {
		let res = await requestSync("/user/info")
		try {
			commit('setUserInfo', res.data.user_info)
			dispatch("setStatus", {
				userInfo: res.data.user_info,
				type: data.type
			})
		} catch (error) {
			console.log(error);
		}
	},
	async setStatus({
		commit
	}, data) {
		// #ifdef MP-WEIXIN || H5
		return new Promise(async (resolve, reject) => {
			let res = await requestSync("/user/status")
			try {
				if (res.code == 200) {
					setStoraged("userStatus", res.data)
					if (data && data.userInfo) {
						commit('loginInfo', {
							status: res.data,
							userInfo: data.userInfo
						});
						if (data.type) {
							if (data.type == 'job') {
								if (res.data.job_status) {
									uni.navigateTo({
										url: '/pages2/regulateJobs',
									});
								} else {
									uni.navigateTo({
										url: `/pages2/postOffer?phone=${data.userInfo.phone}`,
									});
								}
							} else if (data.type == 'resume') {
								if (res.data.resume_status) {
									uni.navigateTo({
										url: `/pages2/regulateResume`,
									});
								} else {
									uni.navigateTo({
										url: `/pages2/postRecruitmentInformation?phone=${data.userInfo.phone}`,
									});
								}

              } else if (data.type == 'storefront') {
                if (res.data.storefront_status) {
                  uni.navigateTo({
                    url: `/shopPackage/manageStore`,
                  });
                } else {
                  uni.navigateTo({
                    url: `/shopPackage/publishStore`,
                  });
                }
							} else if (data.type == 'back') {
								uni.navigateBack({
									delta: 1
								})
							}
						}

					} else if (res.data) {
						state.userStatus = res.data
					}



					resolve({
						status: res.data,
						userInfo: data
					})
				}

			} catch (error) {
				reject(error)
				console.log(error);
			}
		})
		// #endif
		// #ifdef APP-PLUS
		requestSync("/user/status").then(res => {
			if (res.code == 200) {
				setStoraged("userStatus", res.data)
				if (data && data.userInfo) {
					commit('loginInfo', {
						status: res.data,
						userInfo: data.userInfo
					});
					if (data.type) {
						if (data.type == 'job') {
							if (res.data.job_status) {
								uni.navigateTo({
									url: '/pages2/regulateJobs',
								});
							} else {
								uni.navigateTo({
									url: `/pages2/postOffer?phone=${data.userInfo.phone}`,
								});
							}
						} else if (data.type == 'resume') {
							if (res.data.resume_status) {
								uni.navigateTo({
									url: `/pages2/regulateResume`,
								});
							} else {
								uni.navigateTo({
									url: `/pages2/postRecruitmentInformation?phone=${data.userInfo.phone}`,
								});
							}

						} else if (data.type == 'back') {
							uni.navigateBack({
								delta: 1
							})
						}
					}

				} else if (res.data) {
					state.userStatus = res.data
				}
			}else{
					console.log(res)
				
			}
		}).catch(err=>{
			console.log(err)
		})
		// #endif


	},
	async chatLogin({
		commit,
		dispatch
	}, data) {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: "weixin",
				success: async res => {
					console.log(res.code);
					this.code = res.code;
					let params = {
						code: data.code,
						loginCode: res.code,
						device_model: data.deviceModel,
					};
					if (getStoraged("shareUserId")) {
						params.invite_id = JSON.parse(getStoraged(
							"shareUserId"));
					}
					let res2 = await requestSync("/wechat/login", params);
					console.log("res2", res2);
					if (res2.code == 200) {
						setStoraged("authration_token", res2.data.token);
						setStoraged("user_id", res2.data.user_info.id);
						setStoraged("phone", res2.data.user_info.phone);
						// dispatch('setStatus')
						setTimeout(() => {
							console.log("211", data.type);
							dispatch('setUserInfo', {
								userInfo: res2.data.user_info,
								type: data.type
							}); //用户信息加密保存到数据库中，保存
						}, 1000)

						// resolve(true)
					} else {
						reject(false)
					}

					// const fn = () => {
					//   return new Promise(async (resolve, reject) => {
					//     await this.setUserInfo();
					//     await this.setStatus();
					//     resolve(true);
					//   });
					// };
					// await fn();
					// setTimeout(() => {
					//   this.$emit("reload");
					// }, 1000);

					// setTimeout(() => {
					//   if (this.$getStoraged("phone").length > 0) {
					//     this.isLogin = true;
					//     this.phone = JSON.parse(this.$getStoraged("phone"));
					//   } else {
					//     this.isLogin = false;
					//   }
					//   console.log(this.getUserStatus.job_status);
					//   if (this.getUserStatus.job_status) {
					//     _this.$togo("/pages2/regulateJobs");
					//   } else {
					//     _this.$togo("/pages2/postOffer", {
					//       phone: res2.data.user_info.phone
					//     });
					//   }
					// }, 0);
				},
				fail: e => {
					console.log(1, e);
				},
			});
		})
		console.log(commit, data);
	}
}

const getters = {
	getUserInfo: state => {
		return state.userInfo
	}, //获取用户信息
	getUserStatus: state => state.userStatus, //获取用户发布状态
	getSystemInfo: state => state.systemInfo,
	getPhone: state => {
		if (state.userInfo) {
			return state.userInfo.phone
		} else {
			return ""
		}
	}, //获取用户发布状态
	showMfsjf: state => state.showMfsjf
}


export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
}